import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Box,
  Typography,
  Alert,
  Chip,
  Grid,
  FormControlLabel,
  Switch,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { createRule } from 'src/api/auto-accounting';

interface CreateRuleForm {
  ruleName: string;
  ruleType: string;
  remark: string;
  amount: number;
  payUserName: string;
  forUserName: string;
  payWay: string;
  payPlat: string;
  frequency: string;
  frequencyValue: number;
  startDate: string;
  endDate: string;
  isActive: boolean;
}

interface AutoAccountingRuleCreateDialogProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export function AutoAccountingRuleCreateDialog({
  open,
  onClose,
  onSuccess,
}: AutoAccountingRuleCreateDialogProps) {
  const [form, setForm] = useState<CreateRuleForm>({
    ruleName: '',
    ruleType: '',
    remark: '',
    amount: 0,
    payUserName: '',
    forUserName: '',
    payWay: '',
    payPlat: '',
    frequency: '',
    frequencyValue: 0,
    startDate: '',
    endDate: '',
    isActive: true,
  });
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

  const handleSubmit = async () => {
    // 表单验证
    if (!form.ruleName.trim()) {
      setMessage('请输入规则名称');
      setSeverity('error');
      return;
    }
    if (!form.ruleType.trim()) {
      setMessage('请选择规则类型');
      setSeverity('error');
      return;
    }
    if (!form.remark.trim()) {
      setMessage('请输入备注');
      setSeverity('error');
      return;
    }
    if (!form.payUserName.trim()) {
      setMessage('请输入付款人');
      setSeverity('error');
      return;
    }
    if (!form.forUserName.trim()) {
      setMessage('请输入收款人');
      setSeverity('error');
      return;
    }
    if (!form.payWay.trim()) {
      setMessage('请选择支付方式');
      setSeverity('error');
      return;
    }
    if (!form.frequency.trim()) {
      setMessage('请选择执行频率');
      setSeverity('error');
      return;
    }

    try {
      setLoading(true);
      const result = await createRule(form);

      if (result.code === '00000') {
        setMessage('规则创建成功');
        setSeverity('success');
        setTimeout(() => {
          onSuccess();
          resetForm();
        }, 1000);
      } else {
        setMessage(result.message || '创建规则失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error creating rule:', error);
      setMessage('创建规则失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setForm({
      ruleName: '',
      ruleType: '',
      remark: '',
      amount: 0,
      payUserName: '',
      forUserName: '',
      payWay: '',
      payPlat: '',
      frequency: '',
      frequencyValue: 0,
      startDate: '',
      endDate: '',
      isActive: true,
    });
    setMessage('');
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  const handlePatternChange = (value: string) => {
    setForm({ ...form, ruleType: value });
    // 自动生成描述
    if (value && !form.remark) {
      setForm(prev => ({
        ...prev,
        ruleType: value,
        remark: `自动匹配包含"${value}"的交易记录`
      }));
    }
  };

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
      <DialogTitle>
        <Box display="flex" alignItems="center" gap={1}>
          <Iconify icon="eva:plus-circle-fill" color="primary.main" />
          创建自动记账规则
        </Box>
      </DialogTitle>
      
      <DialogContent>
        {message && (
          <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
            {message}
          </Alert>
        )}

        <Box sx={{ pt: 1 }}>
          <Grid container spacing={2}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="规则名称"
                value={form.ruleName}
                onChange={(e) => setForm({ ...form, ruleName: e.target.value })}
                placeholder="例如：餐饮消费规则"
                helperText="为规则起一个容易识别的名称"
              />
            </Grid>
            
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>规则类型</InputLabel>
                <Select
                  value={form.ruleType}
                  onChange={(e) => setForm({ ...form, ruleType: e.target.value })}
                  label="规则类型"
                >
                  <MenuItem value="PERIODIC">周期性</MenuItem>
                  <MenuItem value="TRIGGER">触发式</MenuItem>
                  <MenuItem value="SMART">智能</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="备注"
                value={form.remark}
                onChange={(e) => setForm({ ...form, remark: e.target.value })}
                multiline
                rows={2}
                placeholder="描述这个规则的用途和适用场景"
                helperText="详细描述规则的用途，帮助后续维护"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="金额"
                type="number"
                value={form.amount}
                onChange={(e) => setForm({ ...form, amount: Number(e.target.value) })}
                placeholder="0"
                helperText="设置固定金额，0表示不固定"
                InputProps={{
                  startAdornment: <Typography sx={{ mr: 1 }}>¥</Typography>,
                }}
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>执行频率</InputLabel>
                <Select
                  value={form.frequency}
                  onChange={(e) => setForm({ ...form, frequency: e.target.value })}
                  label="执行频率"
                >
                  <MenuItem value="DAILY">每天</MenuItem>
                  <MenuItem value="WEEKLY">每周</MenuItem>
                  <MenuItem value="MONTHLY">每月</MenuItem>
                  <MenuItem value="YEARLY">每年</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="付款人"
                value={form.payUserName}
                onChange={(e) => setForm({ ...form, payUserName: e.target.value })}
                placeholder="例如：张三"
                helperText="设置付款人姓名"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="收款人"
                value={form.forUserName}
                onChange={(e) => setForm({ ...form, forUserName: e.target.value })}
                placeholder="例如：李四"
                helperText="设置收款人姓名"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>支付方式</InputLabel>
                <Select
                  value={form.payWay}
                  onChange={(e) => setForm({ ...form, payWay: e.target.value })}
                  label="支付方式"
                >
                  <MenuItem value="CASH">现金</MenuItem>
                  <MenuItem value="BANK_CARD">银行卡</MenuItem>
                  <MenuItem value="ALIPAY">支付宝</MenuItem>
                  <MenuItem value="WECHAT">微信支付</MenuItem>
                  <MenuItem value="OTHER">其他</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="支付平台"
                value={form.payPlat}
                onChange={(e) => setForm({ ...form, payPlat: e.target.value })}
                placeholder="例如：美团、饿了么"
                helperText="设置支付平台或应用"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="频率值"
                type="number"
                value={form.frequencyValue}
                onChange={(e) => setForm({ ...form, frequencyValue: Number(e.target.value) })}
                placeholder="例如：1表示每周一或每月1号"
                helperText="设置具体的频率值"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <FormControlLabel
                control={
                  <Switch
                    checked={form.isActive}
                    onChange={(e) => setForm({ ...form, isActive: e.target.checked })}
                  />
                }
                label="启用规则"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="开始日期"
                type="date"
                value={form.startDate}
                onChange={(e) => setForm({ ...form, startDate: e.target.value })}
                InputLabelProps={{ shrink: true }}
                helperText="规则生效的开始日期"
              />
            </Grid>

            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="结束日期"
                type="date"
                value={form.endDate}
                onChange={(e) => setForm({ ...form, endDate: e.target.value })}
                InputLabelProps={{ shrink: true }}
                helperText="规则生效的结束日期"
              />
            </Grid>
          </Grid>
        </Box>
      </DialogContent>
      
      <DialogActions>
        <Button onClick={handleClose}>取消</Button>
        <Button onClick={handleSubmit} variant="contained" disabled={loading}>
          {loading ? '创建中...' : '创建规则'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
